import { RouterView, createRouter, createWebHashHistory } from 'vue-router';
import { h } from 'vue'

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        { path: '/', redirect: "/login" },
        {
            path: '/login',
            component: () =>
                import ('./components/Login.vue')
        },
        {
            path: '/home',
            component: () =>
                import ('./components/Home.vue'),
            redirect: '/home/users',
            children: [{
                    path: 'users',
                    component: { render: () => h(RouterView) },
                    children: [{
                            path: '',
                            component: () =>
                                import ('./components/subcomponents/MyUsers.vue')
                        },
                        {
                            path: ':id',
                            name: 'details',

                            component: () =>
                                import ('./components/user/MyUserDetail.vue'),
                            props: true

                        }
                    ]
                },

                {
                    path: 'rights',
                    component: () =>
                        import ('./components/subcomponents/MyRights.vue')
                },
                {
                    path: 'goods',
                    component: () =>
                        import ('./components/subcomponents/MyGoods.vue')
                }, {
                    path: 'orders',
                    component: () =>
                        import ('./components/subcomponents/MyOrders.vue')
                },
                {
                    path: 'settings',
                    component: () =>
                        import ('./components/subcomponents/MySettings.vue')
                },
                {
                    path: 'menu',
                    component: () =>
                        import ('./components/subcomponents/MyMenu.vue')
                },
                // {
                //     path: '/users/:id', // 动态路由  匹配到的id  会作为props 传递给组件
                //     name: 'user',
                //     props: true, // 开启props传参  会把params  作为props 传递给组件



                //     component: () =>
                //         import ('./components/user/MyUserDetails.vue')
                // }

            ]
        }
    ]
})
export default router;

// 路由守卫

router.beforeEach((to, from, next) => {
    // 如果访问的是登录页面，直接执行下一个钩子函数
    if (to.path === '/login')
        return next()
            // 获取Token值
    const token = localStorage.getItem('token')
    console.log(token)
    if (!token) {
        // Token值不存在，强制跳转到登录页面
        return next('/login')
    }
    // 存在Token值，直接执行下一个钩子函数
    next()
})